<?php
	
	use Workerman\Worker;
	use Workerman\Mysql;
	use \Workerman\Lib\Timer;
	use \Workerman\Protocols\Http;
	use \Workerman\WebServer;
	
	require_once IA_LIB . "/class/debug.class.php";	
	require_once IA_LIB . "/../Libs/class/token.class.php";
    require_once IA_LIB . "/class/PHPMailer/PHPMailer.php";	
    require_once IA_LIB . "/class/PHPMailer/SMTP.php";	
    require_once IA_LIB . "/class/PHPMailer/Exception.php";
	$include_path = IA_LIB.'/action_web/' ;
	

	// 这里监听8080端口，如果要监听80端口，需要root权限，并且端口没有被其它程序占用
	$webserver = new WebServer(SERVER_HOST_2 .':'. WEB_PORT);
	// 类似nginx配置中的root选项，添加域名与网站根目录的关联，可设置多个域名多个目录
	
	$webserver->addRoot('main.com', IA_ROOT. '/../../web/');
	// 设置开启多少进程
	$webserver->count = 3;
	
	// 创建一个Worker监听5052端口，使用tcp协议通讯
	$net_worker = new Worker(SERVER_HOST_2.":".INTERFACE_WEB_PORT);
	// 启动4个进程对外提供服务
    $net_worker->name = "interface_web";
	$net_worker->count = 1;	//5
	//服务启动
	$net_worker->onWorkerStart = function($worker) use($include_path) {
		Trigger\Client::connect(SERVER_HOST, TRIGGER_PORT);
		require_once IA_LIB . "/function/comm.func.php";
        
		//sql_queryExec("set global event_scheduler = on;");
		// 批量加载文件
		include_files($include_path);
	};


	function include_files($include_path){
		$dirs=scandir($include_path );
        foreach($dirs as $v){
        	$dir = $include_path.$v ;
        	if($v=='.' || $v=='..' || !is_dir($dir)  ){
        		continue;
        	}
			foreach(glob($dir.'/*.php') as $start_file)
			{
				require_once $start_file ;
			}
        }


	}


	
	//reload服务
	$net_worker->onWorkerReload = function($worker){
		Trigger\Client::connect(SERVER_HOST, TRIGGER_PORT);
		require_once IA_ROOT . "/../Libs/function/comm.func.php";
		// 批量加载文件
		include_files($include_path);
	};
	
	
	//关闭服务/udp无效
	$net_worker->onWorkerStop = function($worker){

	};
	
	
	//客户端链接/udp无效
	$net_worker->onConnect = function($connection){
		//echo "new connection from ip " . $connection->getRemoteIp() . "\n";
	};
	
	
	//客户端断开链接
	$net_worker->onClose = function($connection){
		//echo "connection closed\n";
	};

	
	
	// 接收数据的event
	$net_worker->onMessage = function($connection, $data) use($net_worker){
      
		$ret = action_switch_web($data); 
		$connection->send($ret);
	};
	
	// 解释recv data, 跳转对应的action
	function action_switch_web($recv_data){
		// //var_dump($recv_data);
       
		$jObj = null;
		Http::header("Access-Control-Allow-Origin: *");
		Http::header("Content-type: application/json");
		Http::header("Access-Control-Allow-Headers:access_token");
		// For HTTP 
		try{
			//var_dump( $_SERVER['REQUEST_METHOD']  );
            // 判断http是get方式请求还是post方式请求
			if($_SERVER['REQUEST_METHOD'] == "GET"){
				$action = $_SERVER['REQUEST_URI'];
				if(strpos($action,"?")){
					$action = strstr($action,"?",true);
				}
                $jObj = $_GET ;
            }else{
            	// //var_dump( $GLOBALS['HTTP_RAW_POST_DATA']  );
                $action = $_SERVER['REQUEST_URI'];
				$jObj = $_POST ;
            }
			$action = ltrim($action, "/");
			
		}catch(Exception $e){
			Debug::Assert($e->getMessage());
		}
		//@Debug::Assert($jObj['action']);
		// 检查是否存在action参数
		if(empty($action)){
			// var_dump($recv_data["server"]);
			$obj = new stdClass();
			$obj->action = "";
			$obj->errcode = 4001;
			$obj->errmsg = "error JSON format command ['action' parameter does not exist]";
			return json_encode($obj);
		}
		
		// 判断是否get_token请求，如果是校验账号密码
		if($action == "get_token"){
			$username = @$jObj['param']["username"];
			$password = @$jObj['param']["password"];
			$ret = Token::login($username,$password);
			$obj = new stdClass();
			$obj->action = "result_get_token";
			if($ret["error_code"] != 0){
				$obj->errcode = $ret["error_code"];
				$obj->errmsg = $ret["error_msg"];
				$obj->rtval = "";
			}else{
				$obj->errcode = $ret["error_code"];
				$obj->errmsg = "";
				$obj->rtval = $ret["data"];
			}
			return json_encode($obj);

		}
		// 检查是否存在头部或上传参数中，是否存在access_token参数
		$header_access_token = @$recv_data["server"]["HTTP_ACCESS_TOKEN"];
		$param_access_token = @$jObj["access_token"];
		$access_token = "";
		if(!empty($header_access_token)){
			$access_token = $header_access_token;
		}elseif(!empty($param_access_token)){
			$access_token = $param_access_token;
		}
		
		if($access_token == ""){
			$obj = new stdClass();
			$obj->action = "result_".$action;
			$obj->errcode = 203;
			$obj->errmsg = "error JSON format command ['access_token' parameter does not exist]";
			//var_dump($recv_data["server"]["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]);
			return json_encode($obj);
		}

		// 判断access_token值是否正确，并且有效
		$ret_check = Token::checkAccessToken($access_token);
		if($ret_check["error_code"] != 0){
			$obj = new stdClass();
			$obj->action = "result_".$action;
			$obj->errcode = $ret_check["error_code"];
			$obj->errmsg = $ret_check["error_msg"];
			$obj->rtval = "";
			return json_encode($obj);

		}
		
		
		$rtval = "";
		$r = NULL; 
		try{
			$className = $action;

			$fun_obj = call_user_func(array($className, "create"));
			$r = $fun_obj->entry($jObj);
			
			if(empty($r))
				throw new Exception("Process function failed");
			if(gettype($r["rtval"]) == "object"){
				if(array_key_exists("error",$r["rtval"]) || array_key_exists("chunkIndex",$r["rtval"])){
					return json_encode($r["rtval"]);
				}
			}
            
			$obj = new stdClass();
			$obj->action = "result_" . $action;
			$obj->errcode = 0;
			$obj->errmsg     = "";
			$obj->rtval   = $r["rtval"];
			return json_encode($obj);
		
		}catch(Exception $exp){
			echo $exp->getMessage();
			$obj = new stdClass();
			$obj->action = "";
			$obj->errcode = 4001;
			$obj->errmsg = "No Action";
			return json_encode($obj);
		}catch(Error $err){
			$obj = new stdClass();
			$obj->action = "";
			$obj->errcode = 4001;
			$obj->errmsg = "No Action";
			return json_encode($obj);
		}

        /*if(!empty($tirggerval)){
            Trigger\Client::publish($action, json_decode(json_encode($tirggerval), true));
        }*/
		
		
	}
	
	
	// 如果不是在根目录启动，则运行runAll方法
	if(!defined('GLOBAL_START')){
		Worker::runAll();
	}
	
	
?>

